<template>
	<view class="equip_detail">
		<NavigationTitle :title="type=='edit'?'设备详情':'新增设备'" style="color: #000;background: #fff;position: fixed;width: 100%;z-index: 5;">
			<template slot="left_con">
				<image class="back_icon" src="@/static/common/back.png" mode="widthFix" @tap="backSelf" />
			</template>
		</NavigationTitle>
		<view class="status-bar"></view>
		<view class="main">
			<uni-forms ref="deviceForm" :modelValue="baseFormData" class="form_main" :rules="rules">
				<uni-forms-item label="设备编号:" required name="deviceId">
					<uni-easyinput v-model="baseFormData.deviceId" placeholder="请输入设备编号"
						:disabled="!authorList.includes('system_device_edit')" />
				</uni-forms-item>
				<uni-forms-item label="设备名称:" required name="deviceName">
					<uni-easyinput v-model="baseFormData.deviceName" placeholder="请输入设备名称"
						:disabled="!authorList.includes('system_device_edit')" />
				</uni-forms-item>
				<uni-forms-item label="设备类型:" required name="deviceType">
					<uni-data-select v-model="baseFormData.deviceType" :localdata="deviceType" placeholder="请输入设备类型"
						:disabled="!authorList.includes('system_device_edit')"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="设备状态:" required name="deviceStatus">
					<uni-data-select v-model="baseFormData.deviceStatus" :localdata="deviceStatus" placeholder="请输入设备名称"
						:disabled="!authorList.includes('system_device_edit')"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="检测设备:" name="gpsNumber">
					<uni-data-select v-model="baseFormData.gpsNumber" :localdata="ssDevice" placeholder="请输入设备类型"
						:disabled="!authorList.includes('system_device_edit')"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="绑定用户:" name="users">
					<view class="users_box" @click="()=>toggle(users)">
						<text>{{users}}</text>
					</view>
					<!-- <uni-easyinput type="textarea" v-model="users" placeholder="请选择设备绑定用户" :adjust-position='false'
						:disabled="!authorList.includes('system_device_edit')"
						@focus="(e)=>toggle(e,users)"></uni-easyinput> -->
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="subUser" style="width: 50%; margin: auto;">提交</button>
		</view>
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<DaTreeVue2 ref="DaTreeRef" :data="userTree" labelField="title" valueField="id" defaultExpandAll
					:showCheckbox="true" :defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange" />
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import NavigationTitle from '@/components/navigationTitle'
	import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
	import {
		showToastMsg,
	} from '@/utils/format.js'
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	export default {
		components: {
			NavigationTitle,
			DaTreeVue2
		},
		computed: {
			...mapGetters(['projectId', 'authorList', 'deviceType', 'deviceStatus','device'])	
		},
		data() {
			return {
				type:'add',
				rules:{
					deviceId: {
						rules: [{
							required: true,
							errorMessage: '设备编号不能为空！'
						}]
					},
					deviceName: {
						rules: [{
							required: true,
							errorMessage: '设备名称不能为空！'
						}]
					},
					deviceType: {
						rules: [{
							required: true,
							errorMessage: '设备类型不能为空！'
						}]
					},
					deviceStatus: {
						rules: [{
							required: true,
							errorMessage: '设备状态不能为空！'
						}]
					}
				},
				baseFormData: {},
				users:'',
				optionType: [],
				optionStatus: [],
				userTree: [],
				userList: [],
				defaultCheckedKeysValue: [],
				checkedKey: '',
				rootNodeKeys: [],
				ssDevice:[],
			}
		},
		onShow() {
			this.optionType = this.deviceType || []
			this.optionStatus = this.deviceStatus || []
			
		},
		async onLoad(option) {
			await this.getUserTree()
			await this.getStartStopDevice()
			console.log(this.deviceStatus)
			if(option.type=='edit'){
				this.baseFormData =  this.device || {}
				if(this.device.users.length>0){
					this.getUsers(this.device.users)
				}
			} 
			this.type = option.type
			
		},
		methods: {
			backSelf() {
				uni.navigateBack({
					delta: 1
				})
			},
			async getStartStopDevice(){
				if(!this.projectId) return 
				let res = await this.$api.getStartStopDevice({
					projectId:this.projectId
				}).catch(err=>{
					console.log(err)
				})
				if(res?.code==200){
					res.data.map(v=>{
						v.text = v.deviceName
						v.value = v.deviceId
					})
					this.ssDevice = res.data
				}
			},
			getUsers(arr){
				let key =[],str='',checked=[]
				console.log(this.userList)
				this.userList.length>0&&this.userList.map(v=>{
					arr.map(i=>{
						if(v.userId==i){
							if(str=='') str=v.nickName
							else str+=","+v.nickName
							key.push(v.treeId)
							checked.push(v.userId)
						}
					})
				})
				this.defaultCheckedKeysValue = key
				this.users = str
				this.checkedKey = checked
				console.log(arr)
			},
			handleTreeChange(allSelectedKeys, currentItem) {
				let arr = ''
				let str = ''
				if (allSelectedKeys.length !== 0) {
					allSelectedKeys.map(v => {
						let index = v.indexOf('-')
						if (index != -1) {
							if(arr=='') arr = v.slice(index + 1)
							else arr+=','+v.slice(index + 1)
						}
						this.userList.map(i=>{
							if(i.treeId==v){
								if(str=='') str=i.nickName
								else str+=","+i.nickName
							}
						})
					})
				}
				this.users= str
				this.checkedKey = arr

			},
			async getUserTree() {
				const res = await this.$api.getUserTree({
					projectId: this.projectId
				}).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					let arr = []
					if (res.data.length != 0) {
						res.data.map(v => {
							this.rootNodeKeys.push(v.id)
							if (v.userDtos.length > 0) {
								v.userDtos.map(i => {
									i.treeId=v.id + '-' + i.userId
									arr.push(i)
									v.children.push({
										id: v.id + '-' + i.userId,
										title: i.nickName + '+' + i.userPhone
									})
								})
							}
						})
					}
					this.userList = arr
					this.userTree = res.data
				}
			},
			toggle(data) {
				let arr = []
				if(data){
					data.split(",").length>0&&data.split(",").map(v=>{
						this.userList.map(i=>{
							if(i.nickName==v){
								arr.push(i.treeId)
							}
						})
					})
				}
				this.defaultCheckedKeysValue = arr
				this.$refs.popup.open('bottom')
			},
			subUser() {
				let param = {},str=""
				if(this.type=='edit'&&!this.authorList.includes('system_device_edit')) return showToastMsg('无修改权限！')
				if(!this.projectId) return 
				this.checkedKey.length!=0&&this.checkedKey.map(v=>{
					if(str=='') str=v
					else str+=','+v
				})
				this.$refs.deviceForm.validate().then(res => {
					param = res
					param.users = str
					param.project = this.projectId
					if(this.type=='add') this.addEquip(param)
					else if(this.type=='edit') this.editEquip(param)
				}).catch(err => {
					console.log(err)
				})

			},
			async addEquip(data) {
				
				const res = await this.$api.addEquipment(data).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					setTimeout(()=>{this.backSelf()},1000)
				}
				showToastMsg(res.msg)
			},
			async editEquip(data) {
				if(this.device.id) data.id = this.device.id
				else return 
				const res = await this.$api.editEquipment(data).catch(err => {
					console.log(err)
				})
				if (res?.code == 200) {
					setTimeout(()=>{this.backSelf()},1000)
				}
				showToastMsg(res.msg)
			},
			changeRole(e) {
				console.log(e);
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/assets/styles/global.scss';

	view {
		box-sizing: border-box;
	}

	.equip_detail {
		position: relative;
		height: 100%;
	}

	.form_main {
		padding: 40rpx 20rpx;
		min-height: 550rpx;

		.form-item {
			border-bottom: 1px solid #999;

			&>uni-view {
				margin-bottom: 24rpx;
			}

			.form-item-button {
				color: red;
			}

			.item-title {
				font-size: 32rpx;
			}
		}

		.users_box {
			width: 100%;
			height: 200rpx;
			padding: 10rpx;
			overflow: auto;
			border: 1px solid #ccc;
			border-radius: 20rpx;
			text-align: left;
			line-height: 50rpx;
			&>uni-text {
				font-size: 32rpx;
				word-break:keep-all;
			}
		}

		.uni-forms-item {
			flex-direction: column;

			/deep/ .uni-forms-item__label {
				width: auto;
				white-space: nowrap;
				font-size: 32rpx;
			}

			/deep/ .uni-forms-item__content {
				flex: 1;
				min-height: 70rpx;
				padding: 0 12rpx;
			}

			/deep/ .uni-input-placeholder {
				font-size: 28rpx;
			}
			
			/deep/ .uni-easyinput__placeholder-class{
				font-size: 28rpx;
			}

			/deep/ .uni-select__input-placeholder {
				font-size: 28rpx;
				color: #999;
			}
			/deep/ .is-disabled {
				background-color: #fff !important;
				color: #333;
			}
		}


	}

	.main {
		padding-top: $System__title_height;
	}

	.popup-content {
		max-height: 800rpx;
		min-height: 500rpx;
		overflow: auto;
		z-index: 999;
	}

	.back_icon {
		width: 37upx;
	}
</style>